<template>
  <div class="page">
    <h2>神经调控 — 设备管理与随访监测</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按设备名称/编号/医院搜索" clearable style="flex:1" />
      <el-select v-model="filterStatus" placeholder="状态" style="width:160px">
        <el-option label="全部" :value="''" />
        <el-option label="在线" value="online" />
        <el-option label="离线" value="offline" />
        <el-option label="维护中" value="maintenance" />
      </el-select>
      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openDevice()">新增设备</el-button>
        <el-button @click="exportCSV">导出设备</el-button>
      </div>
    </div>

    <div class="muted">管理设备资产、型号、序列号、软件/固件版本、维护记录；并记录患者随访与治疗依从性、远程监测数据。</div>

    <el-table :data="filteredDevices" stripe border style="width:100%;margin-top:12px">
      <el-table-column prop="name" label="设备名称" width="220" />
      <el-table-column prop="serial" label="序列号" width="180" />
      <el-table-column prop="model" label="型号" width="140" />
      <el-table-column prop="hospital" label="所属机构" width="180" />
      <el-table-column prop="status" label="状态" width="120" />
      <el-table-column prop="lastMaint" label="最近维护" width="140" />
      <el-table-column label="操作" width="320">
        <template #default="{ row }">
          <el-button size="small" @click="openDevice(row.id)">编辑</el-button>
          <el-button size="small" type="info" @click="openMaintenance(row.id)" style="margin-left:8px">维护记录</el-button>
          <el-button size="small" type="success" @click="openFollowups(row.id)" style="margin-left:8px">随访监测</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="设备编辑" :model-value="showDeviceEditor" width="760px" @close="closeDeviceEditor">
      <el-form :model="deviceForm" label-width="140px">
        <el-form-item label="设备名称">
          <el-input v-model="deviceForm.name" />
        </el-form-item>
        <el-form-item label="序列号">
          <el-input v-model="deviceForm.serial" />
        </el-form-item>
        <el-form-item label="型号">
          <el-input v-model="deviceForm.model" />
        </el-form-item>
        <el-form-item label="所属机构">
          <el-input v-model="deviceForm.hospital" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="deviceForm.status" style="width:160px">
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="维护中" value="maintenance" />
            <el-option label="停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="软件/固件版本">
          <el-input v-model="deviceForm.firmware" placeholder="例如：v1.2.3" />
        </el-form-item>
        <el-form-item label="备注/位置">
          <el-input type="textarea" v-model="deviceForm.notes" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDeviceEditor">取消</el-button>
        <el-button type="primary" @click="saveDevice">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog title="维护记录" :model-value="showMaint" width="720px" @close="closeMaintenance">
      <div v-if="maintRecords">
        <el-table :data="maintRecords" style="width:100%" size="small" border>
          <el-table-column prop="date" label="日期" width="140" />
          <el-table-column prop="engineer" label="工程师" width="140" />
          <el-table-column prop="type" label="类型" width="120" />
          <el-table-column prop="notes" label="说明" />
        </el-table>
        <div style="margin-top:12px;display:flex;gap:8px">
          <el-button @click="openNewMaint">新增维护记录</el-button>
          <div style="flex:1"></div>
          <div class="muted">最近维护：{{currentDevice && currentDevice.lastMaint}}</div>
        </div>
      </div>
      <template #footer>
        <el-button @click="closeMaintenance">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog title="随访与监测" :model-value="showFollowups" width="900px" @close="closeFollowups">
      <div v-if="followups">
        <el-table :data="followups" style="width:100%" border>
          <el-table-column prop="date" label="随访日期" width="140" />
          <el-table-column prop="patient" label="患者" width="160" />
          <el-table-column prop="ptom" label="主要症状/评分" width="180" />
          <el-table-column prop="adherence" label="依从性" width="120" />
          <el-table-column prop="deviceStatus" label="设备状态" width="120" />
          <el-table-column prop="notes" label="备注" />
          <el-table-column label="操作" width="160">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="editFollowup(row.id)">编辑</el-button>
              <el-button size="danger" type="text" @click="deleteFollowup(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top:12px;display:flex;gap:8px;align-items:center">
          <el-button type="primary" @click="openNewFollowup">新增随访</el-button>
          <el-button @click="exportFollowups">导出随访</el-button>
          <div style="flex:1"></div>
        </div>
      </div>
      <template #footer>
        <el-button @click="closeFollowups">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog title="新增维护记录" :model-value="showNewMaint" width="560px" @close="showNewMaint=false">
      <el-form :model="newMaintForm" label-width="120px">
        <el-form-item label="日期">
          <el-date-picker v-model="newMaintForm.date" type="date" placeholder="选择日期" style="width:200px" />
        </el-form-item>
        <el-form-item label="工程师">
          <el-input v-model="newMaintForm.engineer" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="newMaintForm.type" style="width:200px">
            <el-option label="例行" value="routine" />
            <el-option label="故障修复" value="repair" />
            <el-option label="软件更新" value="fw" />
          </el-select>
        </el-form-item>
        <el-form-item label="说明">
          <el-input type="textarea" v-model="newMaintForm.notes" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showNewMaint=false">取消</el-button>
        <el-button type="primary" @click="saveNewMaint">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog title="新增随访" :model-value="showNewFollowup" width="720px" @close="showNewFollowup=false">
      <el-form :model="newFollowupForm" label-width="140px">
        <el-form-item label="随访日期">
          <el-date-picker v-model="newFollowupForm.date" type="date" placeholder="选择日期" style="width:200px" />
        </el-form-item>
        <el-form-item label="患者">
          <el-input v-model="newFollowupForm.patient" />
        </el-form-item>
        <el-form-item label="主要评分/症状">
          <el-input v-model="newFollowupForm.ptom" placeholder="如：HAM-D 15 / 症状改善" />
        </el-form-item>
        <el-form-item label="依从性">
          <el-select v-model="newFollowupForm.adherence" style="width:160px">
            <el-option label="良好" value="good" />
            <el-option label="一般" value="fair" />
            <el-option label="差" value="poor" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="newFollowupForm.deviceStatus" style="width:160px">
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="newFollowupForm.notes" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showNewFollowup=false">取消</el-button>
        <el-button type="primary" @click="saveNewFollowup">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';

const DEFAULT_DEVICES = [
  { id:1, name:'rTMS-2000', serial:'SN-RT2000-001', model:'RT-2000', hospital:'省精神病院', status:'online', firmware:'v1.3.2', lastMaint:'2025-09-10', notes:'主治疗机1' },
  { id:2, name:'tDCS-Pro', serial:'SN-TD-045', model:'TD-100', hospital:'市精神卫生中心', status:'maintenance', firmware:'v2.0.0', lastMaint:'2025-10-01', notes:'更新补丁中' }
];

const DEFAULT_MAINT = {
  1: [ { date:'2025-09-10', engineer:'张工', type:'routine', notes:'例行校准与电极检查' } ],
  2: [ { date:'2025-10-01', engineer:'李工', type:'fw', notes:'固件升级，需重启' } ]
};

const DEFAULT_FOLLOWS = {
  1: [ { id:1, date:'2025-10-05', patient:'王小明', ptom:'HAM-D 18 -> 12', adherence:'good', deviceStatus:'online', notes:'症状改善，继续观察' } ],
  2: [ ]
};

const devices = ref(JSON.parse(JSON.stringify(DEFAULT_DEVICES)));
const maint = reactive(JSON.parse(JSON.stringify(DEFAULT_MAINT)));
const followupsMap = reactive(JSON.parse(JSON.stringify(DEFAULT_FOLLOWS)));

const q = ref('');
const filterStatus = ref('');

const showDeviceEditor = ref(false);
const showMaint = ref(false);
const showFollowups = ref(false);
const showNewMaint = ref(false);
const showNewFollowup = ref(false);

const currentDevice = ref(null);
const maintRecords = ref([]);
const followups = ref([]);

const deviceForm = reactive({ id:null, name:'', serial:'', model:'', hospital:'', status:'online', firmware:'', notes:'' });
const newMaintForm = reactive({ date:'', engineer:'', type:'routine', notes:'' });
const newFollowupForm = reactive({ date:'', patient:'', ptom:'', adherence:'good', deviceStatus:'online', notes:'' });

const filteredDevices = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return devices.value.filter(d=>{
    if(qq && !(d.name.toLowerCase().includes(qq) || d.serial.toLowerCase().includes(qq) || (d.hospital||'').toLowerCase().includes(qq))) return false;
    if(filterStatus.value && d.status !== filterStatus.value) return false;
    return true;
  });
});

function openDevice(id){ if(id){ const it = devices.value.find(d=>d.id===id); if(it){ Object.assign(deviceForm, JSON.parse(JSON.stringify(it))); } } else { Object.assign(deviceForm,{id:null,name:'',serial:'',model:'',hospital:'',status:'online',firmware:'',notes:''}); } showDeviceEditor.value = true; }
function closeDeviceEditor(){ showDeviceEditor.value = false; }
function saveDevice(){ if(!deviceForm.name || !deviceForm.serial){ ElMessage.warning('设备名称与序列号为必填'); return; } if(deviceForm.id){ const it = devices.value.find(d=>d.id===deviceForm.id); if(it) Object.assign(it, JSON.parse(JSON.stringify(deviceForm))); } else { const nid = (devices.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; deviceForm.id = nid; devices.value.push(JSON.parse(JSON.stringify(deviceForm))); maint[nid] = []; followupsMap[nid] = []; } showDeviceEditor.value=false; ElMessage.success('已保存设备信息'); }

function openMaintenance(id){ currentDevice.value = devices.value.find(d=>d.id===id); maintRecords.value = maint[id] ? JSON.parse(JSON.stringify(maint[id])) : []; showMaint.value = true; }
function closeMaintenance(){ showMaint.value = false; currentDevice.value = null; maintRecords.value = []; }
function openNewMaint(){ showNewMaint.value = true; Object.assign(newMaintForm,{date:'',engineer:'',type:'routine',notes:''}); }
function saveNewMaint(){ if(!newMaintForm.date){ ElMessage.warning('请选择日期'); return; } const id = currentDevice.value.id; maint[id] = maint[id] || []; maint[id].push({ date:newMaintForm.date, engineer:newMaintForm.engineer, type:newMaintForm.type, notes:newMaintForm.notes }); const dev = devices.value.find(d=>d.id===id); if(dev) dev.lastMaint = newMaintForm.date; showNewMaint.value=false; ElMessage.success('已保存维护记录'); }

function openFollowups(id){ currentDevice.value = devices.value.find(d=>d.id===id); followups.value = followupsMap[id] ? JSON.parse(JSON.stringify(followupsMap[id])) : []; showFollowups.value = true; }
function closeFollowups(){ showFollowups.value=false; currentDevice.value=null; followups.value = []; }
function openNewFollowup(){ showNewFollowup.value = true; Object.assign(newFollowupForm,{date:'',patient:'',ptom:'',adherence:'good',deviceStatus:'online',notes:''}); }
function saveNewFollowup(){ if(!newFollowupForm.date || !newFollowupForm.patient){ ElMessage.warning('请选择日期并填写患者'); return; } const id = currentDevice.value.id; followupsMap[id] = followupsMap[id] || []; const nid = (followupsMap[id].reduce((s,i)=>Math.max(s,i.id||0),0) || 0) + 1; const item = { id:nid, date:newFollowupForm.date, patient:newFollowupForm.patient, ptom:newFollowupForm.ptom, adherence:newFollowupForm.adherence, deviceStatus:newFollowupForm.deviceStatus, notes:newFollowupForm.notes }; followupsMap[id].push(item); followups.value.push(item); showNewFollowup.value=false; ElMessage.success('已保存随访'); }
function editFollowup(fid){ const id = currentDevice.value.id; const it = (followupsMap[id]||[]).find(x=>x.id===fid); if(!it) return; Object.assign(newFollowupForm, JSON.parse(JSON.stringify(it))); showNewFollowup.value=true; }
function deleteFollowup(fid){ const id = currentDevice.value.id; followupsMap[id] = (followupsMap[id]||[]).filter(x=>x.id!==fid); followups.value = followups.value.filter(x=>x.id!==fid); ElMessage.success('已删除随访'); }

function exportCSV(){ const csv = [ ['id','name','serial','model','hospital','status','firmware','lastMaint','notes'], ...devices.value.map(d=>[d.id,d.name,d.serial,d.model,d.hospital,d.status,d.firmware,d.lastMaint,d.notes]) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='devices.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }
function exportFollowups(){ if(!currentDevice.value){ ElMessage.warning('请选择设备'); return; } const id = currentDevice.value.id; const rows = followupsMap[id]||[]; const csv = [ ['id','date','patient','ptom','adherence','deviceStatus','notes'], ...rows.map(r=>[r.id,r.date,r.patient,r.ptom,r.adherence,r.deviceStatus,r.notes]) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download=(`followups_device_${id}.csv`); document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }

</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>
